import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import {
  Input,
  PageHeader,
  Form,
  Radio,
  Button,
  Space,
  Upload,
  Modal,
  message,
  Tag,
  Row,
} from 'antd';
import TextArea from 'antd/lib/input/TextArea';
import { connect } from 'dva';
import React, { useState, useMemo } from 'react';
import { Dispatch } from 'umi';
import { host } from '../../../../../config/proxy';
import styles from './index.less';
import { ModelState } from '../model';
import { Video } from '../data';
import { UploadFile } from 'antd/lib/upload/interface';
import { UploadChangeParam } from 'antd/es/upload/interface';

export interface VideoEdit {
  dispatch: Dispatch;
  record: Video;
}

type PartialVieo = Partial<Video>;

const VideoEdit = (props: any) => {
  const { record, dispatch } = props;
  const { isAdd = false } = props.history.location.state?.isAdd || {};
  const token = localStorage.getItem('token') || '';
  const [loading, setLoading] = useState(false);
  const [isPreview, setIsPreview] = useState(false); // 是否在预览
  const [previewImg, setPreviewImg] = useState<UploadFile>({} as UploadFile); // 预览的图片
  const [fileList, setfFileList] = useState<UploadFile[]>(() => [
    {
      uid: '-1',
      name: 'image.png',
      status: 'done',
      url: record.poster,
    },
  ] as UploadFile[]);

  console.log(record);

  const handlePreview = (imgItem: UploadFile) => {
    setPreviewImg(imgItem);
    setIsPreview(true);
  };
  const handleModelCancel = () => {
    setIsPreview(false);
  };
  const handlePosterUpload = (e: UploadChangeParam) => {
    console.log(e);
    if (e.file.status === 'uploading') {
      // 必须要设置一下 ,否则无法接触发done状态回调
      setfFileList(e.fileList);
      setLoading(true);
    }
    if (e.file.status === 'done') {
      setLoading(false);
      let url = e.file.response.data.url;
      setVitem({ poster: url });
      setfFileList(e.fileList);
    }
  };

  const handleRadioChange = (e: any) => {
    console.log(e.target.value);
    setVitem({ playStatus: e.target.value });
  };

  const setVitem = (newData: PartialVieo) => {
    dispatch({
      type: 'video/setItem',
      payload: { ...record, ...newData },
    });
  };

  const handleSubmitCapture = async () => {
    let res;
    let obj = { ...record };
    delete obj.source1;
    delete obj.source2
    if (isAdd) {
      res = await dispatch({
        type: 'video/addOne',
        payload: obj,
      });
      console.log('🚀 ~ file: index.jsx ~ line 75 ~ handleSubmitCapture ~ res', res);
    } else {
      res = await dispatch({
        type: 'video/updateOne',
        payload: obj,
      });
    }
    if (res.code === 200) {
      message.success({
        content: isAdd ? '添加成功' : '修改成功！',
      });
      history.back();
      dispatch({
        type: 'video/setVitem',
        payload: {},
      });
    }
  };

  /**
   *  表单值改变事件
   */
  const handleValuesChange = (obj: PartialVieo) => {

    setVitem(obj);
  };

  return (
    <div className={styles.container}>
      <PageHeader
        className="site-page-header"
        onBack={() => history.back()}
        ghost={false}
        title="视频编辑"
      />
      <div className={styles.form}>
        <Form
          initialValues={record}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 6 }}
          onValuesChange={handleValuesChange}
          onSubmitCapture={handleSubmitCapture}
        >
          <Form.Item label="视频名称" name="title">
            <Input></Input>
          </Form.Item>
          <Form.Item label="视屏封面">
            <Upload
              action={`${host}/file/upload`}
              maxCount={1}
              listType="picture-card"
              fileList={fileList}
              onPreview={handlePreview}
              onChange={handlePosterUpload}
              headers={{ Authorization: token }}
              showUploadList={true}
            >
              <div>
                {loading ? <LoadingOutlined></LoadingOutlined> : <PlusOutlined></PlusOutlined>}
                <div style={{ marginTop: 8 }}>上传</div>
              </div>
            </Upload>
          </Form.Item>
          <Form.Item label="发布日期" name="releaseDate">
            <Input></Input>
          </Form.Item>
          <Form.Item label="作者" name="author">
            <Input></Input>
          </Form.Item>
          <Form.Item label="标签" name="label">
            <Input></Input>
          </Form.Item>
          <Form.Item label="视频简介" name="intro">
            <TextArea placeholder="请输入描述"></TextArea>
          </Form.Item>
          <Form.Item label="总集数" name="totals">
            <Input></Input>
          </Form.Item>

          <Form.Item label="已更新至" name="current">
            <Input></Input>
          </Form.Item>
          <Form.Item label="更新周期" name="updatePeriod">
            <Input placeholder="备注信息"></Input>
          </Form.Item>
          <Form.Item label="播放状态">
            <Radio.Group value={record.playStatus} onChange={handleRadioChange}>
              <Radio value={1}>正常</Radio>
              <Radio value={0}>已关闭</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ span: 16 }} label="资源列表">
            <Space style={{ marginLeft: 10 }} direction="vertical" size={30}>
              <Row gutter={[20, 20]}>
                {/* <Col span={24}>col</Col> */}
                <Tag color="#108ee9">播放地址一</Tag>
              </Row>
              <Row gutter={20}>
                {/* <Col span={24}>col</Col> */}
                <Tag color="#108ee9">播放地址一</Tag>
              </Row>
            </Space>
            <Row>
              <Button style={{ marginTop: 20 }} type="primary" htmlType="submit">
                新增资源类型
              </Button>
            </Row>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
            <Space size={40}>
              <Button type="default" onClick={() => history.back()}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确认
              </Button>
            </Space>
          </Form.Item>
        </Form>

        {/* 查看大图 */}
        <Modal
          visible={isPreview}
          title={previewImg?.name || '图片预览'}
          onCancel={handleModelCancel}
          okText="关闭"
          footer={null}
        >
          <img
            alt="example"
            style={{ width: '100%' }}
            src={previewImg?.thumbUrl || previewImg?.url}
          />
        </Modal>
      </div>
    </div>
  );
};

const mapStateToProps = ({ video }: { video: ModelState }) => {
  return {
    record: video.item
  };
};
export default connect(mapStateToProps)(VideoEdit);
